import Vue from "vue";
import Router from "vue-router";
import { getToken } from "@/core/util/tokenUtil";
import { reloadRouter,doRouterTree,getDynamicsRouters, setLocalItem,removeLocalItem,getLocalItem} from "@/core/util/jehcUtil.js";
import { async } from "q";
Vue.use(Router);
// 解决报错
const originalPush = Router.prototype.push
const originalReplace = Router.prototype.replace
// push
Router.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
// replace
Router.prototype.replace = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}

const createRouter = () =>
  new Router({
      mode: 'hash',
      scrollBehavior: () => ({ y: 0 }),
      routes: [
        {
          path: "/",
          redirect: "/dashboard",
          meta:{
            title:'首页',
            canClose: false,
          },
          component: () => import("@/view/layout/layout"),
          children: [
            {
              path: "/dashboard",
              name: "dashboard",
              meta:{
                title:'首页',
                canClose: false,
              },
              component: () => import("@/view/dashboard.vue")
            },
            {
              path: "/builder",
              name: "builder",
              meta:{
                title:'更换主题',
                canClose: true,
              },
              component: () => import("@/view/builder.vue")
            }
          ]
        },
        {
          path: "/",
          component: () => import("@/view/login"),
          children: [
            {
              name: "login",
              path: "/login",
              meta:{
                title:'登录',
                canClose: true,
              },
              component: () => import("@/view/login.vue")
            },
            {
              name: "register",
              path: "/register",
              meta:{
                title:'注册',
                canClose: true,
              },
              component: () => import("@/view/sys/register/register.vue")
            }
          ]
        },
        
        {
          path: "/500",
          name: "500",
          meta:{
            title:'500',
            canClose: true,
          },
          component: () => import("@/view/sys/error/500.vue"),
        },
        // {
        //   path: "/404",
        //   name: "404",
        //   component: () => import("@/view/sys/error/404.vue")
        // },
        // {
        //   path: "*",
        //   redirect: "/404"
        // },
      ]
  })
 
const router = createRouter()

export default router;

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}
const JEHC_ROUTER_NEED_LOAD = "JEHC_ROUTER_NEED_LOAD";
let flag = 0;
router.beforeEach((to,from,next) => {  
  let isReq = true;
  let isLogin = false; 
  let isSetLoad = false;
  if (!getToken() && to.path.indexOf('/login')==-1) {   // 检测登录Token权限  
    flag = 0; 
    next({ path: "/login" })
  }else if(to.path === '/login'){
    isReq = false;//无需重新到后台请求
    isLogin = true;
    next()//表示不会再次调用router.beforeEach()进行循环      
    return  //需要进行return 否则出现死循环    
  }else{ 
    if(flag === 0 || getLocalItem(JEHC_ROUTER_NEED_LOAD) === "1"){          
      resetRouter(); 
      removeLocalItem(JEHC_ROUTER_NEED_LOAD);
      getDynamicsRouters(isReq,isSetLoad).then(res=>{      
        router.options.routes = res;     
        if(null != res && res.length>0){         
          router.addRoutes(res) //动态添加路由 
          flag = 1;          
        }
        router.replace(to)  //重点代码 解决刷新页面 路由空白      
      });        
    }else{
      next()//表示不会再次调用router.beforeEach()进行循环     
    }  
  }
  setTimeout(() => {  // 每次更改路线时滚动页面至顶部
    window.scrollTo(0, 0);
  }, 100);
});

router.afterEach(() => {

});

// /**
//  * 
//  */
// export function initRouter(isReq){
//   console.log("initRouter",initRouter);  
//   resetRouter(); 
//   getDynamicsRouters(isReq).then(res=>{    
//     router.options.routes = res     
//     if(null != res && res.length>0){         
//       router.addRoutes(res) //动态添加路由 
//     }
//   });  
// }